package multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

import constants.NetworkConstants;

public class MulticastCommsClient {

	
	//The goal of this class is to provide a quick way to send messages from a client to a listening server
	//The connection to the group will be on a request basis, joining and leaving the group each time.
	private String groupAddress;
	private int portNumber;
	private InetAddress myAddress ;
	
	public MulticastCommsClient() {
		this.groupAddress = NetworkConstants.DEFAULT_ANNOUNCEMENT_GROUP ;
		this.portNumber = NetworkConstants.DEFAULT_ANNOUNCEMENT_PORT ;
		try {
			this.myAddress = InetAddress.getLocalHost() ;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	MulticastCommsClient(String hostname, int portNumber){
		this.groupAddress = hostname;
		this.portNumber = portNumber;
		try {
			this.myAddress = InetAddress.getLocalHost() ;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void sendMessage(String message){
		MulticastSocket ms;
		InetAddress ia = null;
		try {
			ia = InetAddress.getByName(this.groupAddress);
			ms = new MulticastSocket();
			ms.joinGroup(ia);
			byte[] data = message.getBytes() ;
			DatagramPacket dp = new DatagramPacket(data, data.length,ia,this.portNumber);
			ms.send(dp);
			ms.leaveGroup(ia) ;
			ms.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	public InetAddress getMyAddress(){
		return this.myAddress;
	}
}
